package com.server.core.action;

import com.server.core.domain.Request;
import com.server.core.domain.Response;
import com.server.core.domain.Result;
import com.server.core.exception.FilterNotPassException;
import com.server.core.exception.NoSuchResourceException;
import com.server.core.util.JsonUtil;
import io.netty.handler.codec.http.HttpResponseStatus;

import java.lang.reflect.Method;

/**
 * @desc action抽象类
 */
public abstract class AbstractAction {
    /**
     * @param request
     * @param response
     * @desc 处理action
     */
    public void doAction(Request request, Response response, Method method, AbstractAction action) throws Exception {

        String result = JsonUtil.ResultGenerator.OK.getResult().toString();
        if (method != null) {
            result = method.invoke(action, request, response).toString();
            ///如果是重定向的请求
            if (result.startsWith("redirect:")) {
                response.doRedirect(result.substring(result.indexOf(":") + 1), response);
                return;
            }
        }
        response.setContent(result.getBytes());
        response.sendText();
    }

    public static void doErr(Exception e, Response response) {
        Result result = new Result();

        if (NoSuchResourceException.class.isInstance(e)) {
            response.setStatus(HttpResponseStatus.NOT_FOUND);
            result.setCode(404);
            result.setMsg("Not Found");
        } else if (e instanceof NullPointerException) {
            response.setStatus(HttpResponseStatus.NOT_FOUND);
            result.setCode(400);
            result.setMsg("Bad Request");
        } else if (e instanceof FilterNotPassException) {
            response.setStatus(HttpResponseStatus.FORBIDDEN);
            result.setCode(403);
            result.setMsg("Cannot pass the filter");
        } else {
            response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
            result.setCode(500);
            result.setMsg("Internal Server Error");
        }
        response.setContent(JsonUtil.convert(result).getBytes());
    }
}
